/**
 * @file App.jsx
 * @description 后台管理系统的主应用组件
 */
import React, { useEffect } from 'react';
import { Routes, Route, Navigate } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';
import { initAdminData } from './store/usersSlice';
import AdminLayout from './layouts/AdminLayout';
import Login from './pages/Login';
import Dashboard from './pages/Dashboard';
import OrderManagement from './pages/OrderManagement';
import UserManagement from './pages/UserManagement';
import RoleManagement from './pages/RoleManagement';
import NotFound from './pages/NotFound';
import { initAllData } from './utils/initData';

// 受保护的路由组件
const ProtectedRoute = ({ children, requiredPermission = null }) => {
  const { isAuthenticated, admin } = useSelector((state) => state.adminAuth);
  const { roles } = useSelector((state) => state.users);
  
  if (!isAuthenticated) {
    return <Navigate to="login" replace />;
  }
  
  // 如果指定了所需权限，检查用户是否有该权限
  if (requiredPermission) {
    const userRole = roles.find(role => role.id === admin.roleId);
    const hasPermission = userRole && (
      userRole.permissions.includes('all') || 
      userRole.permissions.includes(requiredPermission)
    );
    
    if (!hasPermission) {
      return <Navigate to="dashboard" replace />;
    }
  }
  
  return children;
};

function App() {
  // 初始化数据
  useEffect(() => {
    initAllData();
  }, []);
  const dispatch = useDispatch();
  
  useEffect(() => {
    // 初始化角色和管理员用户数据
    dispatch(initAdminData());
  }, [dispatch]);
  
  return (
    <Routes>
      <Route path="login" element={<Login />} />
      
      <Route path="/" element={
        <ProtectedRoute>
          <AdminLayout />
        </ProtectedRoute>
      }>
        <Route index element={<Navigate to="dashboard" replace />} />
        <Route path="dashboard" element={<Dashboard />} />
        
        <Route path="orders" element={
          <ProtectedRoute requiredPermission="orders">
            <OrderManagement />
          </ProtectedRoute>
        } />
        
        <Route path="users" element={
          <ProtectedRoute requiredPermission="users">
            <UserManagement />
          </ProtectedRoute>
        } />
        
        <Route path="roles" element={
          <ProtectedRoute requiredPermission="roles">
            <RoleManagement />
          </ProtectedRoute>
        } />
      </Route>
      
      <Route path="*" element={<NotFound />} />
    </Routes>
  );
};

export default App;